package com.pagoda.viewfinder_bridge;


import android.app.Activity;
import android.view.View;

import androidx.fragment.app.Fragment;

import com.pagoda.viewfinder_bridge.provider.ActivityProvider;
import com.pagoda.viewfinder_bridge.provider.FragmentProvider;
import com.pagoda.viewfinder_bridge.provider.IProvider;
import com.pagoda.viewfinder_bridge.provider.ViewProvider;

import java.util.HashMap;
import java.util.Map;

/**
 * E-mail: liaohailong190@foxmail.com
 * Date: 2020/7/16 16:05
 * Description:
 *
 * @author liaohailong
 */
public class ViewFinder {
    public static void inject(Activity activity) {
        IProvider<Activity> provider = new ActivityProvider();
        provider.init(activity);
        inject(activity, provider);
    }

    public static void inject(Fragment fragment) {
        IProvider<Fragment> provider = new FragmentProvider();
        provider.init(fragment);
        inject(fragment, provider);
    }

    public static void inject(Object host, View view) {
        IProvider<View> provider = new ViewProvider();
        provider.init(view);
        inject(host, provider);
    }

    private static final Map<String, Finder<?>> sFinderSave = new HashMap<>();

    private static <HOST> Finder<HOST> getFinder(HOST host) {
        Finder<HOST> finder;
        try {
            String finderClz = host.getClass().getCanonicalName() + "$$Finder";
            finder = (Finder<HOST>) sFinderSave.get(finderClz);
            if (finder == null) {
                Class<?> aClass = Class.forName(finderClz);
                finder = (Finder<HOST>) aClass.newInstance();
                sFinderSave.put(finderClz, finder);
            }
        } catch (Exception e) {
            return null;
        }
        return finder;
    }

    public static <HOST, SOURCE> void inject(HOST host, IProvider<SOURCE> provider) {
        Finder<HOST> finder = getFinder(host);
        if (finder != null) finder.inject(host, provider);
    }

    public static void unbind(Activity activity) {
        IProvider<Activity> provider = new ActivityProvider();
        provider.init(activity);
        unbind(activity, provider);
    }

    public static void unbind(Fragment fragment) {
        IProvider<Fragment> provider = new FragmentProvider();
        provider.init(fragment);
        unbind(fragment, provider);
    }

    public static void unbind(Object host, View view) {
        IProvider<View> provider = new ViewProvider();
        provider.init(view);
        unbind(host, provider);
    }

    private static <HOST, SOURCE> void unbind(HOST host, IProvider<SOURCE> provider) {
        Finder<HOST> finder = getFinder(host);
        if (finder != null) finder.unbind(host, provider);
    }
}
